<script lang="ts" setup>
import {loginWithCode} from '@/api/user'
import type {XCaptchaMethod} from '@/typings/components'

import XInput from '@/components/Form/XInput.vue'
import XButton from '@/components/Form/XButton.vue'
import XGraphicCaptcha from '@/components/Form/XGraphicCaptcha.vue'
import Layout from '@/components/Form/Layout.vue'
import XCaptcha from '@/components/Form/XCaptcha.vue'

const formData = $ref({
    code: '',
    send: false,
    account: '',
    accept: false,
    graphicCaptcha: ''
})

const {base, success} = useToast()
const {switchLoginState} = $(useUser())

const xCaptcha = $ref<XCaptchaMethod>()

async function login() {
    const {code, msg, data} = await loginWithCode({
        code: formData.code,
        phone: formData.account
    })
    if (code !== 0) {
        base(msg || '登录失败！')
        formData.graphicCaptcha = ''
        xCaptcha?.changeCaptcha()
    } else {
        success(msg || '登录成功！')
        switchLoginState(data)
    }
}
</script>

<template>
    <Layout v-model="formData.accept" title="验证码登录">
        <view mt-10>
            <XInput v-model="formData.account" placeholder="请输入账号（手机号或邮箱）"/>
        </view>
        <view m="t-5 b-3">
            <XGraphicCaptcha ref="xCaptcha" v-model="formData.graphicCaptcha" type="login"/>
        </view>
        <view m="t-5 b-3">
            <XCaptcha v-model:send="formData.send" v-model="formData.code" type="login" :form-data="formData"/>
        </view>
        <view my-5>
            <XButton :form-data="formData" @click="login">
                立即登录
            </XButton>
        </view>
        <navigator text="30 #555555" url="/pages/login/password" hover-class="text-blue transition">
            密码登录
        </navigator>
    </Layout>
</template>

<style lang="scss" scoped></style>
